package cn.edu.scau.dormitory_management_system.util;

import cn.edu.scau.dormitory_management_system.constant.FilePath;
import cn.edu.scau.dormitory_management_system.exception.pojo.MyException;
import cn.edu.scau.dormitory_management_system.enums.ExceptionMsgEnum;
import cn.hutool.core.date.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

/**
 * @author djc
 * @date 2021/8/8
 * @time 15:48
 */
public class PoiUtil {

    static  {
        File tmpFile = new File(FilePath.TEMP_PATH);
        if(!tmpFile.exists()) {
            tmpFile.mkdir();
        }
    }

    public static void createExcelFile(int option, List<?> tableContent) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);

        //ExcelUtil初始化
        List<String> title = ExcelUtil.getTitleByOption(option);
        int n = title.size();
        for (int col = 0; col < n; col++) {
            row.createCell(col).setCellValue(title.get(col));
        }

        for (int i = 0; i < tableContent.size(); i++) {
            Row cells = sheet.createRow(i + 1);
            for (int j = 0; j < n; j++) {
                cells.createCell(j);
            }

            Object object = tableContent.get(i);
            Class<?> clazz = object.getClass();
            Field[] fields = clazz.getDeclaredFields();
            int k = 0;

            for (Field field : fields) {
                /**
                 * 注意是否存在不需要字段,跳过
                 * 变量成员的顺序必须和数据库字段的顺序一致
                 */
                if ("serialVersionUID".equals(field.getName())) continue;

                field.setAccessible(true);
                Class<?> type = field.getType();
                /**
                 * 全转成String输出
                 */
                if (type.getName().endsWith("Timestamp") || type.getName().endsWith("Date")) {
                    try {
                        cells.getCell(k++).setCellValue(DateUtil.formatDateTime((Date) field.get(object)));
                    } catch (Exception e) {
                        throw new MyException(ExceptionMsgEnum.POI_UTIL_FAILURE);
                    }
                } else {
                    try {
                        if(field.getName().equals("sex")) {
                            String sex = field.get(object).toString();
                            if("0".equals(sex)) {
                                cells.getCell(k++).setCellValue("女");
                            }else {
                                cells.getCell(k++).setCellValue("男");
                            }
                        }else if("status".equals(field.getName())) {
                            if(field.get(object).toString().equals("1")) {
                                cells.getCell(k++).setCellValue("是");
                            }else {
                                cells.getCell(k++).setCellValue("否");
                            }
                        }else {
                            cells.getCell(k++).setCellValue(field.get(object).toString());
                        }
                    } catch (Exception e) {
                        throw new MyException(ExceptionMsgEnum.POI_UTIL_FAILURE);
                    }
                }
            }
        }

        createExcelFile(workbook, ExcelUtil.getFileNameByOption(option));
    }

    private static void createExcelFile(Workbook workbook, String fileName) {
        OutputStream stream = null;
        try {
            File newName = new File(FilePath.TEMP_PATH + File.separator + fileName + ".xlsx");
            stream = new FileOutputStream(newName.getAbsoluteFile());
            workbook.write(stream);
        } catch (IOException e) {
            FileUtil.deleteFile(FilePath.TEMP_PATH);
            throw new MyException(ExceptionMsgEnum.CREATE_FILE_ERROR);
        } finally {
            IOUtil.closeQuietly(workbook);
            IOUtil.closeQuietly(stream);
        }
    }

}
